package com.thinkingcoder.tccache;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

@Component
public class TcApplicationListener implements ApplicationListener<ApplicationEvent> {

    AtomicInteger index = new AtomicInteger(0);

    @Autowired
    List<TcPlugin> plugins;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        int seq = index.getAndIncrement();
        System.out.println(seq + " event: " + event.getClass().getName());
        System.out.println(seq + " event.getSource() => " + event.getSource());

        if (event instanceof ApplicationReadyEvent are) {
            for (TcPlugin plugin : plugins) {
                plugin.init();
                plugin.startup();
            }
        } else if (event instanceof ContextClosedEvent cce) {
            for (TcPlugin plugin : plugins) {
                plugin.shutdown();
            }
        }
    }

}
